<!--
 * @Author: Liyiqi
 * @LastEditor: Liyiqi
 * @Date: 2020-07-23 10:22:13
 * @LastEditTime: 2021-09-10 14:25:28
 * @Description: 角色首页
-->
<template>
  <div class="source" v-loading="pageLoading" element-loading-text="loading">
    <!-- <h1>{{$t('attributesManagement')}}</h1> -->
    <el-form label-width="160px" :model="searchModel" ref="searchForm" class="search-form" size="small">
      <Search-style :isShowFilter="isShowFilter">
        <el-row :gutter="20" slot="noFilterContent">
          <el-col :span="10">
            <el-form-item label="角色名称" prop="roleName">
              <el-input
                v-model="searchModel.roleName"
                @input="searchModel.roleName=searchModel.roleName.replace(/[^\a-\z\A-\Z0-9\40\u4E00-\u9FA5]/g,'')"
                placeholder="角色名称"
                clearable
                @keyup.enter.native.prevent="searchForm"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="角色编号" prop="bocRoleId">
              <el-input
                v-model="searchModel.bocRoleId"
                @input="searchModel.bocRoleId=searchModel.bocRoleId.replace(/[^\a-\z\A-\Z0-9\40\u4E00-\u9FA5]/g,'')"
                placeholder="角色编号"
                clearable
                @keyup.enter.native.prevent="searchForm"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" slot="noFilterContent">
          <el-col :span="10">
            <el-form-item label="创建时间" prop="bocRoleId">
              <div class="block">
                <el-date-picker
                  v-model="searchModel.createTime"
                  type="daterange"
                  range-separator="至"
                  :picker-options="pickerOptions"
                  :default-value="[new Date(), new Date()]"
                  value-format="yyyy-MM-dd"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                ></el-date-picker>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="更新时间" prop="bocRoleId">
              <div class="block">
                <el-date-picker
                  v-model="searchModel.updateTime"
                  type="daterange"
                  range-separator="至"
                  :picker-options="pickerOptions"
                  :default-value="[new Date(), new Date()]"
                  value-format="yyyy-MM-dd"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                ></el-date-picker>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-button
          @click="resetForm()"
          icon="el-icon-refresh-left"
          class="reset-btn"
          slot="searchBtn"
        >重置</el-button>
        <el-button
          @click="searchForm"
          icon="el-icon-search"
          class="search-btn"
          slot="resetBtn"
        >查询</el-button>
      </Search-style>
    </el-form>
    <div style="margin-top:10px">
      <el-button
        @click="synchroData"
        size="mini"
        style="margin-bottom:0 !important"
        v-if="$auth('systemCenter:permissionManagement:synchronousData')"
      >同步数据</el-button>
      <!-- <div class="timeSort">
        <span>排序</span>
        <el-select
          v-model="searchModel.timeSort"
          @change="sortChange"
          size="mini"
          >
            <el-option
              label="创建时间"
              value="createTime"
            ></el-option>
            <el-option
              label="更新时间"
              value="updateTime"
            ></el-option>
          </el-select>
      </div> -->
    </div>
    <div class="mb-lg">
      <v-table
        :data="tableData"
        size="mini"
        ref="multipleTable"
        :listLoading="listLoading"
        loadingText="loading"
        :paginationTotal="totalNum"
        v-on:handleSelectionChange="handleSelectionChange"
        v-on:pageSizeChange="pageSizeChange"
        v-on:currentPageChange="currentPageChange"
        border
        pagination
      >
        <!-- <el-table-column
          type="selection"
          :selectable="getColSelectAble"
          align="center"
          width="55"
        >
        </el-table-column> -->
        <el-table-column label="角色名称" align="center" :show-overflow-tooltip="true" min-width="130px">
          <template slot-scope="scope">{{scope.row.roleName}}</template>
        </el-table-column>
        <el-table-column label="角色编号" align="center" :show-overflow-tooltip="true" min-width="160px">
          <template slot-scope="scope">{{scope.row.bocRoleId}}</template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" :show-overflow-tooltip="true" min-width="160">
          <template slot-scope="scope">{{scope.row.createTime | timestampToChange("time")}}</template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" :show-overflow-tooltip="true" min-width="160">
          <template slot-scope="scope">{{scope.row.updateTime | timestampToChange("time")}}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="170px" fixed="right" v-if="$auth('systemCenter:permissionManagement:rolePermission')">
          <template slot-scope="scope">
            <span @click="editRole(scope.row)" class="editLink">配置角色权限</span>
          </template>
        </el-table-column>
      </v-table>
    </div>
  </div>
</template>
<script>
import VTable from '@/components/PageTable/index'
import SearchStyle from '@/views/components/SearchStyle'
import { searchRole, changeStatus, synchronousRole } from '@/api/role'
export default {
  name: 'roleList',

  components: {
    VTable,
    SearchStyle
  },

  data () {
    return {
      searchModel: {
        displayStart: 0,
        displayLength: 10,
        roleName: '',
        bocRoleId: '',
        createTime: [],
        updateTime: [],
        timeSort: ''
      },
      timeData: {
        createTimeFrom: '',
        createTimeTo: '',
        updateTimeFrom: '',
        updateTimeTo: ''
      },
      totalNum: 0,
      isShowFilter: false,
      tableData: [],
      selsctList: [],
      idList: [],
      useType: '',
      startUpdateDate: '',
      endUpdateDate: '',
      disableRow: false,
      useRow: false,
      useBtnAvailable: false,
      disableBtnAvailable: false,
      listLoading: false,
      pageLoading: false,
      pickerOptions: {
        disabledDate (time) {
          // 如果没有后面的-8.64e7就是不可以选择今天的
          return time.getTime() > Date.now() // - 8.64e7
        }
      }
    }
  },

  mounted () {
    this.fetchList()
    // this.attributetypes = this.lookupItems.MDSETYPE
  },

  methods: {
    // 加载table数据
    fetchList () {
      if (!this.$auth('systemCenter:permissionManagement:list')) {
        // 权限控制
        const msg = '您没有权限'
        this.$alert(msg)
        return false
      }
      this.pageLoading = true
      this.timeData = {
        createTimeFrom: this.searchModel.createTime ? new Date(this.searchModel.createTime[0] + ' ' + '00:00:00').getTime() : '',
        createTimeTo: this.searchModel.createTime ? new Date(this.searchModel.createTime[1] + ' ' + '23:59:59').getTime() : '',
        updateTimeFrom: this.searchModel.updateTime ? new Date(this.searchModel.updateTime[0] + ' ' + '00:00:00').getTime() : '',
        updateTimeTo: this.searchModel.updateTime ? new Date(this.searchModel.updateTime[1] + ' ' + '23:59:59').getTime() : ''
      }
      const params = {
        ...this.searchModel,
        ...this.timeData
      }
      searchRole(params).then(response => {
        // 调用接口保存新增修改attribute
        const data = response
        if (data) {
          if (Number(data.code) === 1) {
            this.tableData = data.obj.records
            this.totalNum = data.obj.total
          } else {
            this.$confirm(data.code, {
              confirmButtonText: '确定',
              showCancelButton: false
            })
          }
          this.pageLoading = false
        } else {
          this.pageLoading = false
        }
      })
    },
    // 搜索页面
    searchForm () {
      this.searchModel.displayStart = 0
      this.$refs.multipleTable.restPage()
      this.fetchList()
    },

    // 重置搜索
    resetForm () {
      /* this.isFilter = false */
      this.searchModel.roleName = ''
      this.searchModel.bocRoleId = ''
      this.searchModel.createTime = ''
      this.searchModel.updateTime = ''
      this.searchModel.displayStart = 0
      this.timeData = {}
      this.fetchList()
    },

    // 新增操作
    addRole () {
      this.$router.push({ name: 'roleAdd', params: { id: '' } })
    },

    // 获取多选框内的值
    handleSelectionChange (val) {
      this.idList = []
      this.useRow = false
      this.disableRow = false
      this.selsctList = val
      if (this.selsctList[0].roleStatus === 1) {
        this.disableRow = true
      }
      if (this.selsctList[0].roleStatus === 2) {
        this.useRow = true
      }
      this.selsctList.forEach((e) => {
        this.idList.push(e.id)
      })
    },

    getColSelectAble (row) {
      if (this.disableRow === true && row.roleStatus === 2) {
        return false
      } else if (this.useRow === true && row.roleStatus === 1) {
        return false
      } else {
        return true
      }
    },

    // 启用
    useRole () {
      this.useType = '1'
      this.useBtnAvailable = true
      this.useOrDisable()
      this.useBtnAvailable = false
    },

    useOrDisable () {
      const params = {
        ids: this.idList,
        roleStatus: this.useType
      }
      changeStatus(params).then(response => {
        const data = response
        if (data) {
          if (Number(data.code) === 1) {
            this.fetchList()
          } else {
            this.$confirm(this.$t(data.result.code), {
              confirmButtonText: '确定',
              showCancelButton: false
            })
          }
        }
      })
    },

    sortChange (value) {
      if (value === 'createTime') {
        this.tableData.sort((a, b) => {
          return a.createTime - b.createTime
        })
      } else {
        this.tableData.sort((a, b) => {
          return a.updateTime - b.updateTime
        })
      }
    },

    // 修改page size
    pageSizeChange (size) {
      this.searchModel.displayLength = size
      this.fetchList()
    },

    // 修改current page
    currentPageChange (curPage) {
      this.searchModel.displayStart = curPage - 1
      this.fetchList()
    },

    editRole (row) {
      row.roleAuth = true
      this.$router.push({ name: 'roleEdit', params: { id: row } })
    },
    editData (row) {
      row.dataAuth = true
      this.$router.push({ name: 'dataEdit', params: { id: row } })
    },

    // 同步数据
    synchroData () {
      const timestampChang = this.$root.$options.filters.timestampToChange
      this.startUpdateDate = timestampChang(new Date().getTime()) + '00:00:00'
      this.endUpdateDate = timestampChang(new Date().getTime(), 'time')
      const params = {
        startUpdateDate: this.startUpdateDate,
        endUpdateDate: this.endUpdateDate,
        pageSize: '100'
      }
      synchronousRole(params).then(response => {
        // 调用接口保存新增修改attribute
        const data = response
        if (data) {
          if (Number(data.code) === 1) {
            this.fetchList()
          } else if (Number(data.code) === 101) {
            this.$confirm('数据已经是最新版本', {
              confirmButtonText: '确认',
              showCancelButton: false
            })
          } else {
            this.$confirm(data.code, {
              confirmButtonText: '确认',
              showCancelButton: false
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.timeSort {
  float: right;
  display: flex;
  flex-direction: row;

  span {
    width: 40px;
    display: flex;
    align-items: center;
    padding: 0 10px;
    font-size: 1.3rem;
  }
}
</style>
